<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Operaciones extends CI_Controller {

    public $total_tables = array();
    
    function __construct() {
        parent::__construct();
        $this->load->language('crud_adm_' . $this->config->item('language'), $this->config->item('language'));
        $this->config->load('database_tables');
        $this->total_tables = $this->config->item('dbtables');
    }

    public function index() {
        if (!$this->ion_auth->logged_in()) {
            redirect('crud/login');
        } else {
            $this->load->view('index');
        }
    }
    
    public function guardar($redireccion = null){
        $this->db->insert($this->total_tables['producto'], $_POST);
        $this->session->set_userdata('product_id', $this->db->insert_id());
    }
    
    public function guardar_contenido(){
        foreach($_POST as $key => $value){
            $field = explode("_", $key);
            $user = $this->ion_auth->user()->row();
            if($this->existe_valor('contenido', $field[1])){//update
                $this->db->where('fk_id_contenido', $field[1]);
                $this->db->where('fk_id_empresa', $user->company);
                $this->db->where('fk_id_producto', $this->session->userdata('product_id'));
                $this->db->update($this->total_tables['contenido_producto__nn'], array('valor' => $value));
            }else{//insert
                $data = array(
                    'fk_id_producto' => $this->session->userdata('product_id'),
                    'fk_id_contenido' => $field[1],
                    'valor' => $value,
                    'fk_id_empresa' => $user->company,
                    'usumod' => $user->username
                );
                $this->db->insert($this->total_tables['contenido_producto__nn'], $data);
            }
        }
        redirect('crud/mantenimientos/contenido', 'refresh');
    }
    
    public function guardar_distribucion(){
        foreach($_POST as $key => $value){
            $field = explode("_", $key);
            $user = $this->ion_auth->user()->row();
            if($this->existe_valor('distribucion', $field[1])){//update
                $this->db->where('fk_id_distribucion', $field[1]);
                $this->db->where('fk_id_empresa', $user->company);
                $this->db->where('fk_id_producto', $this->session->userdata('product_id'));
                $this->db->update($this->total_tables['distribucion_producto__nn'], array('valor' => $value));
            }else{//insert
                $data = array(
                    'fk_id_producto' => $this->session->userdata('product_id'),
                    'fk_id_distribucion' => $field[1],
                    'valor' => $value,
                    'fk_id_empresa' => $user->company,
                    'usumod' => $user->row()->username
                );
                $this->db->insert($this->total_tables['distribucion_producto__nn'], $data);
            }
        }
        redirect('crud/mantenimientos/distribucion', 'refresh');
    }
    
    public function guardar_distancia(){
        foreach($_POST as $key => $value){
            $field = explode("_", $key);
            $user = $this->ion_auth->user()->row();
            if($this->existe_valor('distancia', $field[1])){//update
                $this->db->where('fk_id_distancia', $field[1]);
                $this->db->where('fk_id_empresa', $user->company);
                $this->db->where('fk_id_producto', $this->session->userdata('product_id'));
                $this->db->update($this->total_tables['distancia_producto__nn'], array('valor' => $value));
            }else{//insert
                $data = array(
                    'fk_id_producto' => $this->session->userdata('product_id'),
                    'fk_id_distancia' => $field[1],
                    'valor' => $value,
                    'fk_id_empresa' => $user->company,
                    'usumod' => $user->username
                );
                $this->db->insert($this->total_tables['distancia_producto__nn'], $data);
            }
        }
        redirect('crud/mantenimientos/distancia', 'refresh');
    }
    
    private function existe_valor($tabla = null, $field = null, $empresa = null){
        $this->db->where('fk_id_producto', $this->session->userdata('product_id'));
        $this->db->where('fk_id_'.$tabla, $field);
        $this->db->where('fk_id_empresa', 1);
        $this->db->from($this->total_tables[$tabla.'_producto__nn']);
        $query = $this->db->get();
        if($query->num_rows() > 0){
            return true;
        }else{
            return false;
        }
    }
    
    public function guardar_usuario(){
        $data = array();
        foreach($_POST as $key => $value){
            if($key == 'password'){
                if($value != '' && $value == $_POST['password_confirm']){
                    $data[$key] = $value;
                }
            }else{
                if($key != 'password_confirm'){
                    if(strpos($key, 'idi_') !== false){
                        $data[$key] = 'S';
                    }else{
                        $data[$key] = $value;
                    }
                }
            }
        }
        $this->ion_auth->update($this->ion_auth->user()->row()->id, $_POST);
        redirect('crud/perfil', 'refresh');
    }
    
    public function get_municipios(){
        $this->load->model('producto_model');
        $query = $this->producto_model->get_municipio($this->input->post('provincia'));
        $cadena = '';
        foreach ($query->result_array() as $row) {
            $seleccionado = "";
            //if($row['id'] == $defecto){ $seleccionado = "selected"; }else{ $seleccionado = ""; }
            $cadena .= "<option value='".$row['id']."' ".$seleccionado.">".$row['desc']."</option>";
        }
        echo $cadena;
    }
    
    public function seleccionar_producto($idproducto = null, $redireccion = null){
        $this->session->set_userdata('product_id', $idproducto);
        redirect('crud/mantenimientos/'.$redireccion);
    }
    
    public function cerrar_ventas(){
        $this->load->model('producto_model');
        $this->load->library('General');
        $resultado = $this->producto_model->agregar_cierres($this->session->userdata('product_id'),
                                                            $this->general->fec_str_to_ymd($this->input->post('fecini')),
                                                            $this->general->fec_str_to_ymd($this->input->post('fecfin')));
    }
    
    public function cambiar_tarifa(){
        $this->load->model('producto_model');
        $this->load->library('General');
        $num_dias = $this->general->restar_fechas($this->input->post('fecini'), $this->input->post('fecfin'));

        for($x = 0; $x <= $num_dias; $x++){
            $dia = $this->general->sumar_dias($this->input->post('fecini'), $x);
            $this->producto_model->agregar_tarifas($this->session->userdata('product_id'), 
                                                   $this->general->fec_str_to_mysql($dia), 
                                                   $this->input->post('tarifa'));
        }        
    }

    public function eliminar_cierre(){
        $this->load->model('producto_model');
        $this->producto_model->eliminar_cierres($this->input->post('evento'), $this->ion_auth->user()->row()->company);
    }
    
    public function confirmar_reserva(){
        $this->load->model('producto_model');
        $this->producto_model->confirmar_reservas($this->input->post('evento'), $this->ion_auth->user()->row()->company);
    }

    public function cambia_producto_sesion(){
        $this->session->set_userdata('product_id', $this->input->post('p_producto'));
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */